package com.his.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.his.common.PageParam;
import com.his.common.Rsp;
import com.his.entity.Schedule;
import com.his.mapper.ScheduleMapper;
import com.his.service.ScheduleService;
import com.his.utils.MyUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * (Schedule)表服务实现类
 *
 * @author makejava
 * @since 2020-10-26 10:04:37
 */
@Service("scheduleService")
public class ScheduleServiceImpl implements ScheduleService {
    @Resource
    private ScheduleMapper scheduleMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Schedule queryById(Integer id) {
        return this.scheduleMapper.queryById(id);
    }

    /**
     * 查询所有通过实体类属性
     *
     * @param pageParam 分页对象
     * @return 查询的结果
     */
    @Override
    public Rsp queryAll(PageParam<Schedule> pageParam) {
        if(!StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())){
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            PageInfo<Schedule> info = new PageInfo<>(scheduleMapper.queryByUserName(pageParam.getSuperSearchKeyWord()));
            return Rsp.success(info);
        }
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        //排序
        for (int i = 0; i < pageParam.getOrderParams().length; i++) {
            PageHelper.orderBy(pageParam.getOrderParams()[i]);
        }
        PageInfo<Schedule> info = new PageInfo<>(scheduleMapper.queryAll(pageParam.getModel()));
        return Rsp.success(info);
    }

    /**
     * 新增数据
     *
     * @param schedule 排班实例对象
     * @return 实例对象
     */
    @Override
    public Rsp insert(Schedule schedule) {
        if(scheduleMapper.getByTime(MyUtil.dateFormat(schedule.getTime()),schedule.getDepName())>=2){
            return Rsp.fail().msg("当前时间的科室已有两人值班");
        }
       if(scheduleMapper.getByTimeAndUserId(MyUtil.dateFormat(schedule.getTime()),schedule.getUserId())>0) {
           return Rsp.fail().msg("当前时间已安排该人值班");
       }
        return scheduleMapper.insert(schedule)>0?Rsp.success(null):Rsp.fail().msg("添加失败");
    }

    /**
     * 修改数据
     *
     * @param schedule 实例对象
     * @return 实例对象
     */
    @Override
    public Rsp update(Schedule schedule) {
        if(schedule.getId()==null){
            return Rsp.fail().msg("排班表的主键不能为空");
        }
       return  scheduleMapper.update(schedule)>0?Rsp.success(null):Rsp.fail().msg("修改失败");

    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.scheduleMapper.deleteById(id) > 0;
    }

    @Override
    public boolean getSchedule(int userId) {
        return scheduleMapper.getSchedule(userId)>0;
    }
}